<?php
namespace Controllers;

class storeController extends Controller
{
    public function storeList()
    {
        $this->checkAccess($this->getUserId(), '12345');                                  
        $res = $this->container['db']->select($this->storeHouseTable.'(store)', [
            '[><]'.$this->projectTable.'(project)' => 'project_id'
        ], [
            'store.goods_id',
            'store.project_id',
            'store.table_id',
            'store.name',
            'store.type',
            'store.num',
            'store.time',
            'store.for',
            'store.place',
            'store.store_type',
            'store.remain',
            'project.name(project_name)'
        ]);
        return (!$this->container['db']->error()[1])?(json_encode($res)):(self::jsonFail('获取失败'));
    }


    public function storeIn()
    {
        $this->checkAccess($this->getUserId(), '4');                                          
        if($_POST['table_id'])
        {
            // 检查申购表是否合法（状态为3）
            $res = $this->container['db']->select($this->roleApplyTable, 'table_id', [
                'table_id' => $_POST['table_id'],
                'status' => 3
            ]);
            if(!$res) return self::jsonFail('申购表不合法');
            // 入库操作
            $tables_id = $this->container['db']->select($this->roleApplyTable, 'table_id', [
                'merge_id' => $_POST['table_id']
            ]);
            if($tables_id)
            {
                $status = $this->container['db']->action(function($database) use($tables_id) 
                {
                    foreach($tables_id as $key => $table_id) 
                    {
                        @$res = $database->update($this->roleApplyTable, [
                            'status' => 5
                        ], [
                            'table_id' => $table_id
                        ]);
                        if(!$res->rowCount()) return false;
                    }
                    $res1 = $database->update($this->roleApplyTable, [
                        'status' => 5
                    ], [
                        'table_id' => $_POST['table_id']
                    ]);
                    if(!$res1->rowCount()) return false;
                    $goods = $database->select($this->applyTable, '*', [
                        'table_id' => $_POST['table_id'],
                    ]);
                    if(!$goods) return false;
                    $projectId = $database->select($this->roleApplyTable, 'project_id', [
                        'table_id' => $_POST['table_id']
                    ])[0];
                    foreach ($goods as $key => $value) 
                    {
                        // 插入仓库
                        $database->insert($this->storeHouseTable, [
                            'goods_id' => '',
                            'project_id' => $projectId,
                            'table_id' => $_POST['table_id'],
                            'item_id' => $value['item_id'],
                            'store_type' => $value['store_type'],
                            'name' => $value['name'],
                            'type' => $value['type'],
                            'num' => $value['num'],
                            'time' => time(),
                            'for' => $value['for'],
                            'remain' =>  $value['num'],
                            'place' => $value['place']
                        ]);
                        if(!$database->id()) return false;
                        // 插入入库记录
                        $database->insert($this->inRecordTable, [
                            'id' => '',
                            'item_id' => $value['item_id'],
                            'num' => $value['num'],
                            'operator' => $this->payload['username'],
                            'time' => date("Y-m-d",time())                        
                        ]);
                        if(!$database->error()[1])
                        {
                            if(!$database->id()) return false;
                        }
                        else 
                        {
                            return false;
                        }
                    }
                    return true;
                });
                return ($status)?(self::jsonSuccess('入库成功')):(self::jsonFail('入库失败'));
            }
            else
            {
                $status = $this->container['db']->action(function($database)
                {
                    $goods = $database->select($this->applyTable, '*', [
                        'table_id' => $_POST['table_id'],
                    ]);
                    if(!$goods) return false;
                    $projectId = $database->select($this->roleApplyTable, 'project_id', [
                        'table_id' => $_POST['table_id']
                    ])[0];
                    foreach ($goods as $key => $value) 
                    {
                        // 插入仓库
                        $database->insert($this->storeHouseTable, [
                            'goods_id' => '',
                            'project_id' => $projectId,
                            'table_id' => $_POST['table_id'],
                            'item_id' => $value['item_id'],
                            'store_type' => $value['store_type'],
                            'name' => $value['name'],
                            'type' => $value['type'],
                            'num' => $value['num'],
                            'time' => time(),
                            'for' => $value['for'],
                            'remain' =>  $value['num'],
                            'place' => $value['place']
                        ]);
                        if(!$database->id()) return false;
                        // 插入入库记录
                        $database->insert($this->inRecordTable, [
                            'id' => '',
                            'item_id' => $value['item_id'],
                            'num' => $value['num'],
                            'operator' => $this->payload['username'],
                            'time' => date("Y-m-d",time())                        
                        ]);
                        if(!$database->error()[1])
                        {
                            if(!$database->id()) return false;
                        }
                        else 
                        {
                            return false;
                        }
                    }
                    $row = $database->update($this->roleApplyTable, [
                        'status' => 5
                    ], [
                        'table_id' => $_POST['table_id']
                    ]);
                    if(!$row) return false;
                    
                    return true;
                });
                return ($status)?(self::jsonSuccess('入库成功')):(self::jsonFail('入库失败'));
            }
        }
        else 
        {
            return self::jsonFail('请输入申购表id');
        }
    }


    public function inRecordList()
    {
        $this->checkAccess($this->getUserId(), '4');                                          
        $res = $this->container['db']->select($this->inRecordTable, '*');
        return (!$this->container['db']->error()[1])?(json_encode($res)):(self::jsonFail('获取失败'));
    }

    public function outRecordList()
    {
        $this->checkAccess($this->getUserId(), '4');                                          
        $res = $this->container['db']->select($this->outRecordTable, '*');
        return (!$this->container['db']->error()[1])?(json_encode($res)):(self::jsonFail('获取失败'));
    }


    public function receive()
    {
        $this->checkAccess($this->getUserId(), '12345');                                          
        if($_POST['goods_id'] && $_POST['num'])
        {
            if($_POST['num'] < 1) return self::jsonFail('数量不合法');
            // 根据item_id来领用
            // $goods = $this->container['db']->select($this->applyTable.'(apply)', [
            //     '[><]'.$this->roleApplyTable.'(role)' => 'table_id',
            //     '[><]'.$this->projectTable.'(project)' => [
            //         'role.project_id' => 'project_id'
            //     ],
            //     '[><]'.$this->storeHouseTable.'(store)' => 'item_id'
            // ], [
            //     'store.goods_id',
            //     'store.remain',
            //     'apply.table_id',
            //     'project.project_id'
            // ], [
            //     'item_id' => $_POST['item_id'],
            //     'project.user_id' => $this->getUserId(),
            //     'role.status' => 5           
            // ])[0];
            // 根据goods_id来领用
            $goods = $this->container['db']->select($this->storeHouseTable, '*', [
                'goods_id' => $_POST['goods_id']
            ])[0];
            if($goods)
            {
                if($_POST['num'] > $goods['remain']) return self::jsonFail('数量不合法');
                $id = $this->container['db']->insert($this->reTable, [
                    'id' => '',
                    'goods_id' => $goods['goods_id'],
                    'num' => $_POST['num'],
                    'action' => 1,
                    'time' => time(),
                    'project_id' => $goods['project_id'],
                    'table_id' => $goods['table_id'],
                    'item_id' => $goods['item_id']
                ]);
                return ($this->container['db']->id())?(self::jsonSuccess('提交领用表成功')):(self::jsonFail('提交领用表失败'));
            }
            else 
            {
                return self::jsonFail('仓库中无此物品');
            }
        }
        else 
        {
            return self::jsonFail('请输入物品id和数量');
        }
    }

    public function updateRe()
    {
        $this->checkAccess($this->getUserId(), '1');                                          
        if($_POST['re_id'] && $_POST['num'])
        {
            $data = $this->container['db']->update($this->reTable, [
                'num' => $_POST['num']
            ], [
                'status[!]' => 1
            ]);
            return ($data->rowCount())?(self::jsonSuccess('更新成功')):(self::jsonFail('更新失败'));
        }
        else 
        {
            return self::jsonFail('请输入表id或数量');
        }
    }

    public function back()
    {
        $this->checkAccess($this->getUserId(), '12345');                                          
        if($_POST['goods_id'] && $_POST['num'])
        {
            if($_POST['num'] < 1) return self::jsonFail('数量不合法');
            // 根据item_id来领用
            // $goods = $this->container['db']->select($this->applyTable.'(apply)', [
            //     '[><]'.$this->roleApplyTable.'(role)' => 'table_id',
            //     '[><]'.$this->projectTable.'(project)' => [
            //         'role.project_id' => 'project_id'
            //     ],
            //     '[><]'.$this->storeHouseTable.'(store)' => 'item_id'
            // ], [
            //     'store.goods_id',
            //     'store.remain',
            //     'apply.table_id',
            //     'project.project_id'
            // ], [
            //     'item_id' => $_POST['item_id'],
            //     'project.user_id' => $this->getUserId(),
            //     'role.status' => 5           
            // ])[0];
            $goods = $this->container['db']->select($this->storeHouseTable, '*', [
                'goods_id' => $_POST['goods_id']
            ])[0];
            if($goods)
            {
                $id = $this->container['db']->insert($this->reTable, [
                    'id' => '',
                    'goods_id' => $goods['goods_id'],
                    'num' => $_POST['num'],
                    'action' => 0,
                    'time' => time(),
                    'project_id' => $goods['project_id'],
                    'table_id' => $goods['table_id'],
                    'item_id' => $goods['item_id']
                ]);
                return ($this->container['db']->id())?(self::jsonSuccess('提交退库表成功')):(self::jsonFail('提交退库表失败'));
            }
            else 
            {
                return self::jsonFail('仓库中无此物品');
            }
        }
        else 
        {
            return self::jsonFail('请输入物品id和数量');
        }
    }

    public function receiveTable()
    {
        $this->checkAccess($this->getUserId(), '4');                                          
        $res = $this->container['db']->select($this->reTable.'(re)', [
            '[><]'.$this->storeHouseTable.'(store)' => 'goods_id',
            '[><]'.$this->projectTable.'(project)' => [
                're.project_id' => 'project_id'
            ]
        ], [
            're.id(re_id)',
            'project.name(project_name)',
            'store.name(goods_name)',
            're.goods_id',
            're.num',
            're.time',
            're.table_id',
            're.item_id',
            're.project_id',
            're.status'
        ], [
            'action' => 1,
            'status' => 0
        ]);
        return (!$this->container['db']->error()[1])?(json_encode($res)):(self::jsonFail('获取失败'));
    }

    public function dReceiveTable()
    {
        $this->checkAccess($this->getUserId(), '4');                                          
        $res = $this->container['db']->select($this->reTable.'(re)', [
            '[><]'.$this->storeHouseTable.'(store)' => 'goods_id',
            '[><]'.$this->projectTable.'(project)' => [
                're.project_id' => 'project_id'
            ]
        ], [
            're.id(re_id)',
            'project.name(project_name)',
            'store.name(goods_name)',
            're.goods_id',
            're.num',
            're.time',
            're.table_id',
            're.item_id',
            're.project_id',
            're.status'
        ], [
            'action' => 1,
            'status' => 1
        ]);
        return (!$this->container['db']->error()[1])?(json_encode($res)):(self::jsonFail('获取失败'));
    }

    public function myReceiveTable()
    {
        $this->checkAccess($this->getUserId(), '1');                                          
        $res = $this->container['db']->select($this->reTable.'(re)', [
            '[><]'.$this->storeHouseTable.'(store)' => 'goods_id',
            '[><]'.$this->projectTable.'(project)' => [
                're.project_id' => 'project_id'
            ]
        ], [
            're.id(re_id)',
            'project.name(project_name)',
            'store.name(goods_name)',
            're.goods_id',
            're.num',
            're.time',
            're.table_id',
            're.item_id',
            're.project_id',
            're.status'
        ], [
            'action' => 1,
            'project.user_id' => $this->getUserId()
        ]);
        return (!$this->container['db']->error()[1])?(json_encode($res)):(self::jsonFail('获取失败'));
    }   

    public function backTable()
    {
        $this->checkAccess($this->getUserId(), '4');                                          
        $res = $this->container['db']->select($this->reTable.'(re)', [
            '[><]'.$this->storeHouseTable.'(store)' => 'goods_id',
            '[><]'.$this->projectTable.'(project)' => [
                're.project_id' => 'project_id'
            ]
        ], [
            're.id(re_id)',
            'project.name(project_name)',
            'store.name(goods_name)',
            're.goods_id',
            're.num',
            're.time',
            're.table_id',
            're.item_id',
            're.status'
        ], [
            'action' => 0,
            'status' => 0
        ]);
        return (!$this->container['db']->error()[1])?(json_encode($res)):(self::jsonFail('获取失败'));
    }

    public function dBackTable()
    {
        $this->checkAccess($this->getUserId(), '4');                                          
        $res = $this->container['db']->select($this->reTable.'(re)', [
            '[><]'.$this->storeHouseTable.'(store)' => 'goods_id',
            '[><]'.$this->projectTable.'(project)' => [
                're.project_id' => 'project_id'
            ]
        ], [
            're.id(re_id)',
            'project.name(project_name)',
            'store.name(goods_name)',
            're.goods_id',
            're.num',
            're.time',
            're.table_id',
            're.item_id',
            're.project_id',
            're.status'
        ], [
            'action' => 0,
            'status' => 1
        ]);
        return (!$this->container['db']->error()[1])?(json_encode($res)):(self::jsonFail('获取失败'));
    }

    public function myBackTable()
    {
        $this->checkAccess($this->getUserId(), '1');                                          
        $res = $this->container['db']->select($this->reTable.'(re)', [
            '[><]'.$this->storeHouseTable.'(store)' => 'goods_id',
            '[><]'.$this->projectTable.'(project)' => [
                're.project_id' => 'project_id'
            ]
        ], [
            're.id(re_id)',
            'project.name(project_name)',
            'store.name(goods_name)',
            're.goods_id',
            're.num',
            're.time',
            're.table_id',
            're.item_id',
            're.project_id',
            're.status'
        ], [
            'action' => 0,
            'project.user_id' => $this->getUserId()
        ]);
        return (!$this->container['db']->error()[1])?(json_encode($res)):(self::jsonFail('获取失败'));
    }   

    public function receiveCheck()
    {
        $this->checkAccess($this->getUserId(), '14');                                          
        if($_POST['re_id'])
        {
            @$res = $this->container['db']->select($this->reTable.'(re)', [
                '[><]'.$this->storeHouseTable.'(store)' => 'goods_id'
            ], [
                're.num',
                'store.remain',
                're.goods_id'
            ], [
                're.id' => $_POST['re_id'],
                're.status' => 0
            ])[0];
            if($res)
            {
                $actStatus = $this->container['db']->action(function($database) use($res)
                {
                    if($_POST['action'] == 0)
                    {
                        ;
                    }
                    else if($_POST['action'] == 1)
                    {
                        $tmp = $res['remain'] - $res['num'];
                        if($res['num'] > $res['remain']) exit(self::jsonFail('领用数量不合法'));
                        $status = 1;
                        $data = $database->update($this->storeHouseTable, [
                            'remain' => $tmp
                        ], [
                            'goods_id' => $res['goods_id']
                        ]);
                    }
                    else 
                    {
                        return false;
                    }
                    if(isset($data) && $data->rowCount())
                    {
                        $data1 = $database->update($this->reTable, [
                            'status' => 1,
                            'comment' => $_POST['comment']
                        ], [
                            'id' => $_POST['re_id']
                        ]);
                        return ($data1->rowCount())?(true):(false);
                    }
                    else if($_POST['action'] == 0)
                    {
                        @$data1 = $database->update($this->reTable, [
                            'status' => 2,
                            'comment' => $_POST['comment']
                        ], [
                            'id' => $_POST['re_id']
                        ]);
                        return ($data1->rowCount())?(true):(false);
                    }
                    else 
                    {
                        return false;
                    }
                });
                return ($actStatus)?(self::jsonSuccess('领用成功')):(self::jsonFail('领用失败'));
                
            }
            else
            {
                return self::jsonFail('获取失败');
            }
        }
        else 
        {
            return self::jsonFail('请输入领用表id');
        }
    }

    public function backCheck()
    {
        $this->checkAccess($this->getUserId(), '4');                                          
        if($_POST['re_id'] && $_POST['action'])
        {
            @$res = $this->container['db']->select($this->reTable.'(re)', [
                '[><]'.$this->storeHouseTable.'(store)' => 'goods_id'
            ], [
                're.num',
                'store.remain',
                're.goods_id'
            ], [
                're.id' => $_POST['re_id'],
                're.status' => 0
            ])[0];
            if($res)
            {
                $actStatus = $this->container['db']->action(function($database) use($res)
                {
                    $tmp = $res['remain'] + $res['num'];
                    if($_POST['action'] == 0)
                    {
                        ;
                    }
                    else if($_POST['action'] == 1)
                    {
                        $data = $database->update($this->storeHouseTable, [
                            'remain' => $tmp
                        ], [
                            'goods_id' => $res['goods_id']
                        ]);
                    }
                    else 
                    {
                        return false;
                    }
                    if(isset($data) && $data->rowCount())
                    {
                        @$data1 = $database->update($this->reTable, [
                            'status' => 1,
                            'comment' => $_POST['comment']
                        ], [
                            'id' => $_POST['re_id']
                        ]);
                        return ($data1->rowCount())?(true):(false);
                    }
                    else if($_POST['action'] == 0)
                    {
                        $data1 = $database->update($this->reTable, [
                            'status' => 2,
                            'comment' => $_POST['comment']
                        ], [
                            'id' => $_POST['re_id']
                        ]);
                        return ($data1->rowCount())?(true):(false);
                    }
                    else 
                    {
                        return false;
                    }
                });
                return ($actStatus)?(self::jsonSuccess('退库成功')):(self::jsonFail('退库失败'));
            }
            else
            {
                return self::jsonFail('获取失败');
            }
        }
        else 
        {
            return self::jsonFail('请输入退库表id');
        }
    }


    public function storeType()
    {
        $this->checkAccess($this->getUserId(), '14');                                          
        $res = $this->container['db']->select($this->typeStoreTable, '*');
        return (!$this->container['db']->error()[1])?(json_encode($res)):(self::jsonFail('获取失败'));
    }

    public function typeAdd()
    {
        $this->checkAccess($this->getUserId(), '14');                                          
        if($_POST['name'])
        {
            $this->container['db']->insert($this->typeStoreTable, [
                'id' => '',
                'name' => $_POST['name']
            ]);
            return ($this->container['db']->id())?(self::jsonSuccess('增加成功')):(self::jsonFail('增加失败'));
        }
        else 
        {
            return self::jsonFail('请输入名称');
        }
    }

    public function typeUpdate()
    {
        $this->checkAccess($this->getUserId(), '4');                                          
        if($_POST['id'] && $_POST['name'])
        {
            $data = $this->container['db']->update($this->typeStoreTable, [
                'name' => $_POST['name']
            ], [
                'id' => $_POST['id']
            ]);
            return ($data->rowCount())?(self::jsonSuccess('更改成功')):(self::jsonFail('更改失败'));
        }
        else 
        {
            return self::jsonFail('请输入id或者名字');
        }
    }


    public function reTableDel()
    {
        $this->checkAccess($this->getUserId(), '1');                                                  
        if($_POST['re_id'])
        {
            $data = $this->container['db']->delete($this->reTable, [
                'id' => $_POST['re_id'],
                'status[!]' => 1,
 

            ]);
            // var_dump($this->container['db']->log());
            return ($data->rowCount())?(self::jsonSuccess('删除成功')):(self::jsonFail('删除失败'));
        }
        else 
        {
            return self::jsonFail('请输入领用表id');
        }
    }


}